package com.hehe.ConfigInterceptor;
import com.hehe.POJO.User;
import com.hehe.Repository.UserRepository;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


// 管理员权限拦截器
@Component
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private UserRepository userRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())) {
                    String username = cookie.getValue();
                    User user = userRepository.findByUsername(username);
                    if (user != null && user.getRole().equals("admin")) {
                        return true; // 用户是管理员
                    }
                }
            }
        }
//        response.sendRedirect(request.getContextPath() + "/login");
        return false; // 用户未登录或不是管理员，拦截请求并重定向到登录页面
    }
}
